package com.zjf.bbs.service.impl.post;

import java.util.ArrayList;
import java.util.List;

import org.compass.core.CompassCallback;
import org.compass.core.CompassException;
import org.compass.core.CompassHits;
import org.compass.core.CompassSession;

import com.zjf.bbs.databean.SearchResult;
import com.zjf.bbs.entity.Post;

public class QueryCallback implements CompassCallback<SearchResult<Post>> {
	private String keyword;
	private Integer firstIndex;
	private Integer maxResult;

	public QueryCallback(String keyword, Integer firstIndex, Integer maxResult) {
		this.keyword = keyword;
		this.firstIndex = firstIndex;
		this.maxResult = maxResult;
	}

	public SearchResult<Post> doInCompass(CompassSession session) throws CompassException {
		CompassHits  hits = session.find(keyword);
		SearchResult<Post> result = new SearchResult<Post>();
		result.setTotalRecord(hits.length());
		int length = firstIndex+maxResult;
		if(length>hits.length()) length = hits.length();
		List<Post> datas = new ArrayList<Post>();
		for(int i = firstIndex;i<length;i++){
			Post post = (Post) hits.data(i);
			if(hits.highlighter(i).fragment("postTitle")!=null){
				post.setTitle(hits.highlighter(i).fragment("postTitle"));
			}
			String content= null;
			if(hits.highlighter(i).fragment("postContent")!=null){
				content = hits.highlighter(i).fragment("postContent");
				int beginIndex = content.indexOf(keyword) - 100;
				if(beginIndex<0){
					beginIndex = 0;
				}
				int endIndex = content.indexOf(keyword) + 100;
				if(endIndex>content.length()-1){
					endIndex = content.length()-1;
				}
				content =  content.substring(beginIndex, endIndex);
			}
			post.setContent(content);
			datas.add(post);
		}
		result.setDatas(datas);
		return result;
	}

}
